package com.sam.im.heiqun.uis.adapters;

import android.content.Context;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AiteEntivity;
import com.sam.im.heiqun.entities.FriendHeadEntity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.uis.adapters.holder.MessageHolder;
import com.sam.im.heiqun.utils.IMMessageUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.TimeUtil;
import com.zq.utils.StringUtil;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Joe on 2016/12/25.
 */

public class MessageAdpter extends RecyclerView.Adapter<MessageHolder> {

    private static final String TAG = MessageAdpter.class.getSimpleName();
    private Context context;
    private List<MessageEntivity> messageEntivities;
    private MessageListClickListener mItemClickListener;
    private boolean isAiting;
    private OncontentClicklistener oncontentClicklistener;

    //  private String msgid  ;
    public void setAiting(boolean aiting) {
        isAiting = aiting;
        // msgid = id ;
        notifyDataSetChanged();
    }

    public void setOncontentClicklistener(OncontentClicklistener oncontentClicklistener) {
        this.oncontentClicklistener = oncontentClicklistener;
    }

    public MessageAdpter(Context context, List<MessageEntivity> messageEntivities) {
        this.context = context;
        this.messageEntivities = messageEntivities;
    }

    public MessageAdpter(Context context) {
        this.context = context;
    }

    public void refresh(List<MessageEntivity> messageEntivities) {
        this.messageEntivities = messageEntivities;
        notifyDataSetChanged();
    }

    public interface MessageListClickListener {
        void onMessageListClick(View view, int position);

        void onMessageLongListClick(View view, int position);
    }

    public void setItemClickListener(MessageListClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }

    @Override
    public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_message_list, parent, false);
        return new MessageHolder(view, mItemClickListener);
    }

    @Override
    public void onBindViewHolder(MessageHolder holder, final int position) {
        Log.i(TAG, "onBindViewHolder: -----换背景004-------");
        holder.relative_allview.setBackgroundResource(R.drawable.item_bg_selector);
        if (null != messageEntivities && messageEntivities.size() > 0) {//这个地方部分手机偶现空指针BUG，所以添加这个
            MessageEntivity messageEntivity = messageEntivities.get(position);
            Log.i("info", "messageentivity==" + messageEntivity.toString());
            holder.content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    oncontentClicklistener.onclickcontent(position);
                }
            });
            if (messageEntivity == null) {
//                Log.i(TAG, "onBindViewHolder: -----换背景001-------");
                holder.relative_allview.setBackgroundResource(R.drawable.item_bg_selector);
                return;
            }
            if (Constant.TOP_MAN == messageEntivity.getIstop()) {
//                Log.i(TAG, "onBindViewHolder: -----换背景002-------");
                holder.relative_allview.setBackgroundResource(R.drawable.item_bg_selector_top);
            } else {
//                Log.i(TAG, "onBindViewHolder: -----换背景003-------");
                holder.relative_allview.setBackgroundResource(R.drawable.item_bg_selector);
            }


            Log.e("!!!!!!!",messageEntivity.getFromType()+"");
            Log.e("!!!!!!!",messageEntivity.getTime()+"");
            

            if (messageEntivity.getFromType() == Constant.FROM_TYPE_MAM) {
                holder.tvaite.setVisibility(View.GONE);
                switch (messageEntivity.getType()) {
                    case Constant.MESSAGE_TYPR_TEXT:
                        holder.content.setText(messageEntivity.getContent());
                        break;
                    case Constant.MESSAGE_TYPR_BQEMOJI:
                        final String content = messageEntivity.getContent();
                        MsgEntity msgentity = new Gson().fromJson(content, MsgEntity.class);
                        if (msgentity.getMsgCodes() != null && !"".equals(msgentity.getMsgCodes())) {
                            holder.content.setText(context.getResources().getString(R.string.msg_tip_emoj));
                        } else {
                            holder.content.setText(msgentity.getMsgString());
                        }
                        break;
                    case Constant.MESSAGE_TYPR_IMAGE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_image));
                        break;
                    case Constant.MESSAGE_TYPR_FILE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_file));
                        break;
                    case Constant.MESSAGE_TYPR_VOICE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_audio));
                        break;
                    case Constant.MESSAGE_TYPR_REDPACKTE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_red));
                        break;

                    case Constant.MESSAGE_TYPR_REDPACKET_BACK:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_redback));
                        break;
                    case Constant.MESSAGE_TYPR_TRANSFRE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_trans));
                        break;
                    case Constant.MESSAGE_TYPR_TRANSFRE_OK:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_trans));
                        break;
                    case Constant.MESSAGE_TYPR_GET_REDPACKET:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_red_lqn));
                        break;
                    case Constant.MESSAGE_TYPR_LOCATION:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_location));
                        break;
                    case Constant.MESSAGE_TYPR_WITHDRAW:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_getback));
                        break;
                    case Constant.MESSAGE_TYPR_VEDIO:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_smallvedio));
                        break;
                    case Constant.MESSAGE_TYPR_AAMONEY_GET:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_sendaa));
                        break;
                    case Constant.Someone_initiated_the_lucky_red_envelope:
                        holder.content.setText(context.getResources().getString(R.string.launch_lucky_red_envelopes));
                        break;
                    case Constant.MESSAGE_TYPR_READ_DELETE:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_yhjf));
                        break;
                    case Constant.MESSAGE_TYPR_FRIEND_HEAD:
                        holder.content.setText(context.getResources().getString(R.string.msg_tip_friendhead));
                        break;
                    case Constant.MESSAGE_TYPE_INVATE_JOIN_GROUP:
                        holder.content.setText(messageEntivity.getContent());
                        break;
                    case Constant.MESSAGE_TYPE_AGREE_FRIEND_APPLY:
                        holder.content.setText(messageEntivity.getContent());
                        break;
                }
//                Log.i(TAG, "onBindViewHolder: --------------------position"+position);
//                Log.i(TAG, "onBindViewHolder: --------------------messageEntivity.getDestid()"+messageEntivity.getDestid());
                ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, messageEntivity.getDestid());
//                Log.i(TAG, "onBindViewHolder: --------------------imFriendEntivity.getUserId()"+imFriendEntivity.getUserId());
                if (imFriendEntivity != null) {
                   /* Glide.with(context).load(imFriendEntivity.getHeadUrl()).transform(new GlideRoundTransform3(context.getApplicationContext(),5)).centerCrop().placeholder(com.yuyh.library.R.drawable.friend_rest).error(com.yuyh.library.R.drawable.friend_rest)
                            .dontAnimate().into(holder.img);*/
                    GlideUtils.loadHeadCircularImage(context, imFriendEntivity.getHeadUrl(), holder.img);
                    String nickStr = ToolsUtils.getNick(imFriendEntivity);
//                    Log.i(TAG, "onBindViewHolder: --------------------nickStr"+nickStr);
                    holder.nick.setText(nickStr);
                } else {
                    GlideUtils.loadHeadCircularImage(context, "", holder.img);
                }

                if (messageEntivity.getMessageNum() > 0 && messageEntivity.getMessageNum() < 100) {
                    holder.unread_number.setText(messageEntivity.getMessageNum() + "");
                    holder.unread_number.setVisibility(View.VISIBLE);
                } else if (messageEntivity.getMessageNum() > 100) {
                    holder.unread_number.setVisibility(View.VISIBLE);
                    holder.unread_number.setText(Constant.MAX_UNREAD_NUM);
                } else {
                    holder.unread_number.setVisibility(View.GONE);
                }
                //  String timeStr = DateFormatUtil.transForDate(messageEntivity.getTime());
                String timeStr = TimeUtil.getRecentlyTime(messageEntivity.getTime());
                holder.time.setText(timeStr);
            } else if (messageEntivity.getFromType() == Constant.FROM_TYPE_GROUP) {
                String nick = messageEntivity.getNick();
                String nickname = "";
                if (nick != null && !"".equals(nick) && !nick.equals(ToolsUtils.getUser().getNickName())) {
                    nickname = nick + ":";
                }

                switch (messageEntivity.getType()) {
                    case Constant.MESSAGE_TYPR_TEXT:
                        //holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(messageEntivity.getContent());
                        break;
                    case Constant.MESSAGE_TYPR_BQEMOJI:
                        final String content = messageEntivity.getContent();
                        MsgEntity msgentity = new Gson().fromJson(content, MsgEntity.class);
                        if (msgentity.getMsgCodes() != null && !"".equals(msgentity.getMsgCodes())) {
                            // holder.tvaite.setVisibility(View.GONE);
                            holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_emoj));
                        } else {
                            /*if (null != msgentity.getAiteId() && msgentity.getAiteId().size() > 0) {
                                for (int i = 0; i < msgentity.getAiteId().size(); i++) {*/
                            // Long aLong = msgentity.getAiteId().get(i);
                                   /* if (("" + aLong).equals(ToolsUtils.getMyUserId())) {//这里艾特了你
                                     //   holder.tvaite.setVisibility(View.VISIBLE);
                                    }*/
                            Iterator<AiteEntivity> all = AiteEntivity.findAll(AiteEntivity.class);
                            if (!all.hasNext()) {
                                holder.tvaite.setVisibility(View.GONE);
                            } else {
                                while (all.hasNext()) {
                                    //Log.i("info","进来了"+all.next().getDestId()+"  id="+messageEntivity.getDestid());
                                    AiteEntivity next = all.next();
                                    //Log.i("info","进来了"+next.getDestId()+"  id="+messageEntivity.getDestid());
                                    Long destId = next.getDestId();
                                    if ((destId + "").equals(messageEntivity.getDestid() + "")) {
                                        //  Log.i("info","hahaha");
                                        holder.tvaite.setVisibility(View.VISIBLE);
                                        break;
                                    }
                                    // Log.i("info","lalala");
                                    holder.tvaite.setVisibility(View.GONE);
                                }
                            }
                                   /* if (!all.hasNext()){//这里表示列表中没有数据了
                                        Log.i("info","这里进来了");
                                        holder.tvaite.setVisibility(View.GONE);
                                        //Log.i("info","有@消息了");
                                    }*/
                            //  }
                            //}
                            holder.content.setText(nickname + msgentity.getMsgString());
                        }
                        break;
                    case Constant.MESSAGE_TYPR_IMAGE:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_image));
                        break;
                    case Constant.MESSAGE_TYPR_FILE:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_file));
                        break;
                    case Constant.MESSAGE_TYPR_VOICE:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_audio));
                        break;
                    case Constant.MESSAGE_TYPR_REDPACKTE:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_red));
                        break;

                    case Constant.Someone_initiated_the_lucky_red_envelope:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.lucky_red_envelope));
                        break;
                    case Constant.MESSAGE_TYPR_REDPACKET_BACK:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_redback));
                        break;
                    case Constant.MESSAGE_TYPR_GET_REDPACKET:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_red_lqn));
                        break;
                    case Constant.MESSAGE_TYPR_LOCATION:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_location));
                        break;
                    case Constant.MESSAGE_TYPR_WITHDRAW:
                        // holder.tvaite.setVisibility(View.GONE);
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_getback));
                        break;
                    case Constant.MESSAGE_TYPR_VEDIO:
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_smallvedio));
                        break;
                    case Constant.MESSAGE_TYPR_AAMONEY_GET:
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_sendaa));
                        break;
                    case Constant.MESSAGE_TYPR_READ_DELETE:
                        holder.content.setText(nickname + context.getResources().getString(R.string.msg_tip_yhjf));
                        break;
                    case Constant.MESSAGE_TYPE_BE_JOIN_GROUP:
                        holder.content.setText(IMMessageUtil.getBeJoinGroupText(context, messageEntivity.getContent(), messageEntivity.getDestid()));
                        break;
                }
                ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, messageEntivity.getDestid());
                System.out.print("dd"+messageEntivity.getFromType());
                if (imGroupEntivity != null) {
                    GlideUtils.loadHeadGroupCircularImage(context, imGroupEntivity.getHeadUrl(), holder.img);
                    holder.nick.setText(imGroupEntivity.getName());
                } else {
                    holder.img.setImageResource(R.drawable.group_group);
                }
                if (messageEntivity.getMessageNum() > 0 && messageEntivity.getMessageNum() < 100) {
                    Log.i("info", "onBindViewHolder: =======MeesageAdapter============" + messageEntivity.getMessageNum());
                    holder.unread_number.setText(messageEntivity.getMessageNum() + "");
                    holder.unread_number.setVisibility(View.VISIBLE);
                } else if (messageEntivity.getMessageNum() > 100) {
                    holder.unread_number.setVisibility(View.VISIBLE);
                    holder.unread_number.setText(Constant.MAX_UNREAD_NUM);
                } else {
                    holder.unread_number.setVisibility(View.GONE);
                }
                // String timeStr = DateFormatUtil.transForDate(messageEntivity.getTime());
                String timeStr = TimeUtil.getRecentlyTime(messageEntivity.getTime());

                holder.time.setText(timeStr);
            } else if (messageEntivity.getFromType() == Constant.FROM_TYPE_SYS) {

                System.out.print("dd"+messageEntivity.getFromType());
                holder.img.setImageResource(R.mipmap.ic_launcher);
                if (messageEntivity.getType() == Constant.MESSAGE_TYPR_APPLY_FRIEND ||
                        messageEntivity.getType() == Constant.NOTICE_OF_APPLY_FRIEND) {
                    holder.nick.setText(R.string.system_message);

                    Log.i("info", "content===" + messageEntivity.getContent());
                    FriendHeadEntity friendHeadEntity = new Gson().fromJson(messageEntivity.getContent(), FriendHeadEntity.class);
                    if (friendHeadEntity != null) {
                        holder.content.setText(friendHeadEntity.getName() + context.getString(R.string.add_you_to_be_friend));
                    } else {
                        holder.content.setText(messageEntivity.getDestid() + context.getString(R.string.add_you_to_be_friend));
                    }
                    long num = 0;
                    List<MessageEntivity> entivityList = MessageEntivity.find(MessageEntivity.class, "fromid = ? and (type = ? or type=?)", ToolsUtils.getMyUserId() + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + "", Constant.NOTICE_OF_APPLY_FRIEND + "");
                    int size = entivityList.size();
                    for (int i = 0; i < size; i++) {
                        MessageEntivity entivity = entivityList.get(i);
                        num = num + entivity.getMessageNum();
                    }
                    if (num > 0 && num < 100) {
                        holder.unread_number.setText(num + "");
                        holder.unread_number.setVisibility(View.VISIBLE);
                    } else if (num > 100) {
                        holder.unread_number.setVisibility(View.VISIBLE);
                        holder.unread_number.setText(Constant.MAX_UNREAD_NUM);
                    } else {
                        holder.unread_number.setVisibility(View.GONE);
                    }
                } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                        || messageEntivity.getType() == Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP) {
                    long num = 0;
                    setVisible(holder, num);
                    holder.nick.setText(context.getResources().getString(R.string.samim_pay));
                    holder.content.setText(context.getResources().getString(R.string.have_money_get));
                    String timeStr = TimeUtil.getRecentlyTime(messageEntivity.getTime());
                    holder.time.setText(timeStr);
                } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_TOPAYFOR
                        || messageEntivity.getType() == Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP) {
                    long num = 0;
                    setVisible(holder, num);
                    // holder.unread_number.setVisibility(View.GONE);
                    holder.nick.setText(context.getResources().getString(R.string.samim_pay));
                    holder.content.setText(context.getResources().getString(R.string.have_money_pay));
                    String timeStr = TimeUtil.getRecentlyTime(messageEntivity.getTime());
                    holder.time.setText(timeStr);
                } else if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME || messageEntivity.getType() == Constant.MESSAGE_GROUP_ADD_APPLY) {//转让群给我
                    holder.nick.setText(context.getResources().getString(R.string.notice_group));
                    System.out.print("ss"+messageEntivity.getType());
                    System.out.print("ww"+Constant.MESSAGE_GROUP_ADD_APPLY);
                    if (messageEntivity.getType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME) {
                        holder.content.setText(context.getResources().getString(R.string.group_trans));
                    } else {
                        holder.content.setText(context.getResources().getString(R.string.add_group_apply));
                    }
                    long num = 0;
//                    List<MessageEntivity> entivityList = MessageEntivity.find(MessageEntivity.class, "fromid = ? and type = ? ", new String[]{ToolsUtils.getMyUserId() + "", Constant.MESSAGE_TYPR_APPLY_FRIEND + ""});

                    List<MessageEntivity> entivityList = MessageEntivity.find(MessageEntivity.class, " type=? or type=? "
                            , new String[]{Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "", Constant.MESSAGE_GROUP_ADD_APPLY + ""});
                    int size = entivityList.size();
                    for (int i = 0; i < size; i++) {
                        MessageEntivity entivity = entivityList.get(i);
                        num = num + entivity.getMessageNum();
                    }
                    Log.i("info", "onBindViewHolder: ==============num=" + num);
                    if (num > 0 && num < 100) {
                        holder.unread_number.setText(num + "");
                        holder.unread_number.setVisibility(View.VISIBLE);
                    } else if (num > 100) {
                        holder.unread_number.setVisibility(View.VISIBLE);
                        holder.unread_number.setText(Constant.MAX_UNREAD_NUM);
                    } else {
                        holder.unread_number.setVisibility(View.GONE);
                    }
                }
                String timeStr = TimeUtil.getRecentlyTime(messageEntivity.getTime());
                Log.i("info","时间111"+timeStr);
                holder.time.setText(timeStr);
            }
        }
    }

    private void setVisible(MessageHolder holder, long num) {
        List<MessageEntivity> entivityList = MessageEntivity.find(MessageEntivity.class, "type in(?,?,?,?)",
                Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",
                Constant.MESSAGE_TYPR_TOPAYFOR + "",
                Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP + "",
                Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP + "");
        int size = entivityList.size();
        for (int i = 0; i < size; i++) {
            MessageEntivity entivity = entivityList.get(i);
            num = num + entivity.getMessageNum();
        }
        if (num > 0 && num < 100) {
            holder.unread_number.setText(num + "");
            holder.unread_number.setVisibility(View.VISIBLE);
        } else if (num > 100) {
            holder.unread_number.setVisibility(View.VISIBLE);
            holder.unread_number.setText(Constant.MAX_UNREAD_NUM);
        } else {
            holder.unread_number.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return messageEntivities != null ? messageEntivities.size() : 0;
    }

    public interface OncontentClicklistener {
        void onclickcontent(int position);
    }
}